import os
import json
from pathlib import Path

class SessionManager:
    def __init__(self):
        # 获取用户主目录下的配置文件夹路径
        self.config_dir = os.path.expanduser('~/.a-terminal')
        self.sessions_dir = os.path.join(self.config_dir, 'sessions')
        self.ensure_config_dirs()
        
    def ensure_config_dirs(self):
        """确保配置目录存在"""
        os.makedirs(self.config_dir, exist_ok=True)
        os.makedirs(self.sessions_dir, exist_ok=True)
        
    def generate_session_name(self, session_type, session_params, parent_path=''):
        """根据会话类型和参数生成会话名称"""
        if not session_type or not session_params:
            return "新建会话"
            
        base_name = ""
        if session_type == "串口":
            port = session_params.get('port', '')
            # 对于串口类型，只保留最后一个斜杠后的设备名称
            if port and port != "无可用串口":
                port = port.split('/')[-1]
                base_name = f"Serial-{port}"
            else:
                base_name = "Serial-Unknown"
        elif session_type in ["SSH", "Telnet"]:
            host = session_params.get('host', '')
            base_name = f"{session_type}-{host}" if host else f"{session_type}-Unknown"
            
        # 检查名称是否已存在
        name = base_name
        counter = 1
        while True:
            # 构建完整路径进行检查
            full_path = os.path.join(self.sessions_dir, parent_path, name)
            if not os.path.exists(full_path):
                break
            name = f"{base_name}({counter})"
            counter += 1
            
        return name
            
    def create_session(self, name, parent_path='', session_type='', session_params=None):
        """创建新的会话"""
        # 如果是文件夹，使用提供的名称；如果是会话，则自动生成名称
        if session_type and session_params:
            name = self.generate_session_name(session_type, session_params, parent_path)
            
        session_path = os.path.join(self.sessions_dir, parent_path)
        os.makedirs(session_path, exist_ok=True)
        
        # 只有会话类型才创建配置文件
        if session_type:
            # 使用会话名称作为配置文件名，但在显示时不包含后缀
            config_file = os.path.join(session_path, f"{name}.json")
            config = {
                'name': name.replace('.json', ''),  # 确保显示名称不包含.json后缀
                'type': 'session',
                'created_at': str(Path(session_path).stat().st_ctime),
                'session_type': session_type,
                'session_params': session_params or {}
            }
            with open(config_file, 'w', encoding='utf-8') as f:
                json.dump(config, f, ensure_ascii=False, indent=4)
            return config_file
        return session_path
        
    def load_sessions(self):
        """加载所有会话配置和目录结构"""
        sessions = []
        directories = set()
        
        # 遍历所有会话文件和目录
        for root, dirs, files in os.walk(self.sessions_dir):
            # 处理会话文件
            for file_name in files:
                if file_name.endswith('.json'):
                    config_file = os.path.join(root, file_name)
                    with open(config_file, 'r', encoding='utf-8') as f:
                        config = json.load(f)
                        # 只加载会话类型的配置
                        if config.get('type') == 'session':
                            sessions.append({
                                'path': os.path.relpath(os.path.join(root, file_name), self.sessions_dir),
                                'config': config
                            })
            
            # 记录所有目录路径（除了根目录）
            if root != self.sessions_dir:
                rel_path = os.path.relpath(root, self.sessions_dir)
                directories.add(rel_path)
                
                # 添加所有父目录路径
                parent_path = os.path.dirname(rel_path)
                while parent_path:
                    directories.add(parent_path)
                    parent_path = os.path.dirname(parent_path)
        
        # 返回会话和目录信息
        return {
            'sessions': sessions,
            'directories': list(directories)
        }
    
    def rename_session(self, old_path, new_name):
        """重命名会话或文件夹"""
        old_full_path = os.path.join(self.sessions_dir, old_path)
        new_path = os.path.join(os.path.dirname(old_full_path), new_name)
        
        # 重命名目录
        os.rename(old_full_path, new_path)
        
        # 如果是会话，则更新配置文件
        config_file = os.path.join(new_path, 'config.json')
        if os.path.exists(config_file):
            with open(config_file, 'r', encoding='utf-8') as f:
                config = json.load(f)
            config['name'] = new_name
            with open(config_file, 'w', encoding='utf-8') as f:
                json.dump(config, f, ensure_ascii=False, indent=4)
                
    def delete_session(self, path):
        """删除会话或文件夹"""
        full_path = os.path.join(self.sessions_dir, path)
        if os.path.exists(full_path):
            if os.path.isfile(full_path):
                os.remove(full_path)
            else:
                import shutil
                shutil.rmtree(full_path)
    
    def save_session(self, session_path, config):
        """保存会话配置"""
        # 确保父目录存在
        full_path = os.path.join(self.sessions_dir, session_path)
        os.makedirs(os.path.dirname(full_path), exist_ok=True)
        
        # 保存配置文件
        with open(full_path, 'w', encoding='utf-8') as f:
            json.dump(config, f, ensure_ascii=False, indent=4)